﻿using CommunityToolkit.Mvvm.Input;
using DBContext;
using EV.EventBus;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Threading.Tasks;
using ZoneLine.Models;
using ZoneLine.Models.PackageModel;
using ZoneLine.Views;

namespace ZoneLine.ViewModels
{
    public class PackageReplaceViewModel : ViewModelBase
    {
        private IModelDAL _dal;

        private ILogger _logger = LogManager.GetCurrentClassLogger();

        public PackageReplaceViewModel(IModelDAL dal)
        {
            _dal = dal;

            MessageCenter.Unsubscribe(nameof(PackageReplaceViewModel), nameof(PackageReplaceViewModel));

            MessageCenter.Subscribe(nameof(PackageReplaceViewModel), nameof(PackageReplaceViewModel), (ss) =>
            {
                if (InOldPieceCode)
                {
                    OldCode = ss.Source.Payload?.ToString();

                    MessageCenter.PublishAsync(nameof(PackageReplaceView));
                }
                if (InNewPieceCode)
                {
                    NewPieceCode = ss.Source.Payload?.ToString();
                }
                return Task.CompletedTask;
            });
        }

        private bool _inOldPieceCode;

        public bool InOldPieceCode
        {
            get { return _inOldPieceCode; }
            set => SetProperty(ref _inOldPieceCode, value);
        }

        private bool _inNewPieceCode;

        public bool InNewPieceCode
        {
            get { return _inNewPieceCode; }
            set => SetProperty(ref _inNewPieceCode, value);
        }


        private string _oldCode;
        /// <summary>
        /// 
        /// </summary>
        public string OldCode
        {
            get { return _oldCode; }
            set => SetProperty(ref _oldCode, value);
        }


        private PackageResult _targetPackagePiece;
        /// <summary>
        /// 
        /// </summary>
        public PackageResult TargetPackagePiece
        {
            get { return _targetPackagePiece; }
            set => SetProperty(ref _targetPackagePiece, value);
        }


        private string _newPieceCode;

        public string NewPieceCode
        {
            get { return _newPieceCode; }
            set => SetProperty(ref _newPieceCode, value);
        }

        private List<PackageResult> _packageResults;

        public List<PackageResult> PackageResults
        {
            get { return _packageResults; }
            set => SetProperty(ref _packageResults, value);
        }

        private RelayCommand _searchPackageCmd;

        public RelayCommand SearchPackageCmd
        {
            get { return _searchPackageCmd ?? (_searchPackageCmd = new RelayCommand(SearchPackageInfo)); }
        }


        private void SearchPackageInfo()
        {
            if (string.IsNullOrEmpty(OldCode))
            {
                PackageResults = null;
                return;
            }
            try
            {
                LoadingModel.IsBusy = true;
                var packagePieces = _dal.GetModelList<PackageResult>(p => p.Code == OldCode);
                PackageResults = packagePieces;
                LoadingModel.ActionSuccess = true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "search package box err");
                LoadingModel.ActionFailed = true;
            }
        }

        private RelayCommand _replacePieceCmd;

        public RelayCommand ReplacePieceCmd
        {
            get { return _replacePieceCmd ?? (_replacePieceCmd = new RelayCommand(ReplacePiece)); }
        }


        private void ReplacePiece()
        {
            if (_targetPackagePiece == null)
            {
                ShowMsg("请先选中要替换的工件");
                return;
            }
            var confirm = ShowMsg("请确认是否更换该工件", true);
            if (!confirm)
            {
                return;
            }
            try
            {
                var replacedFlag = "_replaced";
                var newPiece = _dal.GetModel<AbsPrintResult>(p => p.Code == NewPieceCode);
                if (newPiece == null)
                {
                    ShowMsg("新输入减震器码查找不到工件");
                    return;
                }

                var newPieceTemp = _dal.GetModel<PackageResult>(p => p.Code == NewPieceCode);
                if (newPieceTemp != null)
                {
                    ShowMsg("新工件已经在其他箱中");
                    return;
                }

                if (string.IsNullOrEmpty(_targetPackagePiece.BoxCode))
                {
                    ShowMsg("旧工件还未装箱");
                    return;
                }

                if (_targetPackagePiece.BoxCode.EndsWith("_replaced"))
                {
                    ShowMsg("旧工件已经被从箱中取出");
                    return;
                }

                if (newPiece.LeftRight != _targetPackagePiece.LeftRight)
                {
                    ShowMsg("新工件和旧工件左右不一样，请确认");
                    return;
                }

                var newModelStr = JsonConvert.SerializeObject(newPiece);
                var packageResultNew = JsonConvert.DeserializeObject<PackageResult>(newModelStr);
                packageResultNew.BoxCode = _targetPackagePiece.BoxCode;
                packageResultNew.PackageTime = DateTime.Now;

                _dal.AddModel<PackageResult>(packageResultNew);
                _targetPackagePiece.BoxCode = _targetPackagePiece.BoxCode + replacedFlag;
                _dal.DeleteModel<PackageResult>(p => p.Id == _targetPackagePiece.Id);

                var replaceRecord = new ReplaceRecordModel();
                replaceRecord.BoxCode = _targetPackagePiece.BoxCode;
                replaceRecord.OldCode = _targetPackagePiece.Code;
                replaceRecord.NewCode = newPiece.Code;
                replaceRecord.CreateTime = DateTime.Now;
                _dal.AddModel(replaceRecord);

                LoadingModel.ActionSuccess = true;
                ShowMsg("产品已经替换完成,请对新工件进行装箱");
            }
            catch (Exception ex)
            {
                LoadingModel.ActionFailed = true;
                _logger.Error(ex, "replace piece err");
            }
        }


        #region 工件替换记录

        private bool _sBoxCode = true;

        public bool SBoxCode
        {
            get { return _sBoxCode; }
            set => SetProperty(ref _sBoxCode, value);
        }

        private bool _sNewCode;

        public bool SNewCode
        {
            get { return _sNewCode; }
            set => SetProperty(ref _sNewCode, value);
        }

        private bool _sOldCode;

        public bool SOldCode
        {
            get { return _sOldCode; }
            set => SetProperty(ref _sOldCode, value);
        }

        public string SearchCode { get; set; }

        private RelayCommand _searchReplaceRecordCmd;

        public RelayCommand SearchReplaceRecordCmd
        {
            get { return _searchReplaceRecordCmd ?? (_searchReplaceRecordCmd = new RelayCommand(SearchReplaceRecord)); }
        }

        private List<ReplaceRecordModel> _replaceRecords;

        public List<ReplaceRecordModel> ReplaceRecords
        {
            get { return _replaceRecords; }
            set => SetProperty(ref _replaceRecords, value);
        }


        private void SearchReplaceRecord()
        {
            ReplaceRecords = null;
            try
            {
                LoadingModel.IsBusy = true;
                if (SBoxCode)
                {
                    ReplaceRecords = _dal.GetModelList<ReplaceRecordModel>(p => p.BoxCode == SearchCode);
                }
                else if (SNewCode)
                {
                    ReplaceRecords = _dal.GetModelList<ReplaceRecordModel>(p => p.NewCode == SearchCode);
                }
                else if (SOldCode)
                {
                    ReplaceRecords = _dal.GetModelList<ReplaceRecordModel>(p => p.OldCode == SearchCode);
                }
                LoadingModel.ActionSuccess = true;
            }
            catch (Exception ex)
            {
                LoadingModel.ActionFailed = true;
                _logger.Error(ex, "查询更换记录失败");
            }
        }


        #endregion
    }
}
